package cn.codewen.shop.servlet;

import cn.codewen.shop.pojo.Category;
import cn.codewen.shop.pojo.Product;
import cn.codewen.shop.service.impl.CategoryServiceImpl;
import cn.codewen.shop.service.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@WebServlet("/admin/product/*")
@MultipartConfig
public class ProductServlet extends BaseServlet {

    private final ProductServiceImpl productService = new ProductServiceImpl();

    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 接收参数
        //2. 处理数据
        //2.1 创建productService对象

        //2.2 调用findAll方法
        List<Product> products = productService.findAll();
        //3. 转发或重定向
        //3.1 传递数据
        request.setAttribute("products", products);
        request.getRequestDispatcher("/admin/product_list.jsp").forward(request, response);


    }

    public void add(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        if (request.getMethod().equals("POST")) {
            String logo = null;
            try {
                //0.处理文件上传
                //0.1 获取上传的文件
                Part part = request.getPart("logo");
                //0.2 获取上传文件的文件名
                String submittedFileName = part.getSubmittedFileName();
                //0.3 获取文件上传的目录
                String path = request.getServletContext().getRealPath("/upload");
                System.out.println(path);
                File file = new File(path);
                if (!file.exists()) {
                    boolean b = file.mkdirs();
                    System.out.println(b);
                }
                String fileName = new Date().getTime() + submittedFileName;
                //0.4 生成一个新的文件名，不重复，数据库存储的就是这个文件名，不重复的
                String filePath = path + "/" + fileName;
                System.out.println("测试产生新的文件名：" + logo);
                //上传文件到指定目录
                part.write(filePath);
                logo = "/upload/" + fileName;
            } catch (Exception e) {
                e.printStackTrace();
            }


            //1.接收参数

            String name = request.getParameter("name");
            //String logo = request.getParameter("logo");
            String price = request.getParameter("price");
            String sale = request.getParameter("sale");
            String stock = request.getParameter("stock");
            String categoryId = request.getParameter("category_id");
            String sort = request.getParameter("sort");
            String status = request.getParameter("status");


            //2.获取数据
            //2.1 创建product对象
            Product product = new Product();
            //2.2 给对象赋值
            product.setName(name);
            product.setLogo(logo);
            product.setPrice(new BigDecimal(price));
            product.setSale(Integer.parseInt(sale));
            product.setStock(Integer.parseInt(stock));
            product.setCategoryId(Integer.parseInt(categoryId));
            product.setStatus(Integer.parseInt(status));
            product.setSort(Integer.parseInt(sort));
            //2.3 创建对象articleService对象
            //2.4 调用insert方法
            productService.insert(product);
            //3.转发或跳转
            response.sendRedirect("/admin/product/list");


        } else {
            //1.接收参数
            //2.获取数据
            CategoryServiceImpl categoryService = new CategoryServiceImpl();
            List<Category> categories = categoryService.findAll();
            //3.转发或跳转
            //3.1 转发数据
            request.setAttribute("categories", categories);
            //3.2 重定向
            request.getRequestDispatcher("/admin/product_add.jsp").forward(request, response);
        }
    }

    public void edit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        //1.接收参数
        String id = request.getParameter("id");
        //2.2 获取当前商品信息
        Product product = productService.getOne(Integer.parseInt(id));
        if (request.getMethod().equals("POST")) {
            // String logo = null;

            //0.处理文件上传
            //0.1 获取上传的文件
            Part part = request.getPart("logo");
            System.out.println("part:" + part.getSize());
            //0.2 判断有没有上传
            if (part.getSize() > 0) {
                //0.2.1 获取上传文件的文件名
                String submittedFileName = part.getSubmittedFileName();
                //0.2.2 获取文件上传的目录
                String path = request.getServletContext().getRealPath("/upload");
                System.out.println(path);
                //0.2.3 判断上传目录存不存在
                File file = new File(path);
                if (!file.exists()) {
                    //如果不存在就创建此目录
                    boolean b = file.mkdirs();
                    System.out.println(b);
                }
                //0.2.4 生成一个新的文件名，不重复，数据库存储的就是这个文件名，不重复的
                String fileName = new Date().getTime() + submittedFileName;
                String filePath = path + "/" + fileName;
                //0.2.5 //上传文件到指定目录
                part.write(filePath);
                //0.2.6 存入数据库logo
                String logo = "/upload/"+fileName;
                product.setLogo(logo);
            }

            //1.接收参数

            String name = request.getParameter("name");
            //String logo = request.getParameter("logo");
            String price = request.getParameter("price");
            String sale = request.getParameter("sale");
            String stock = request.getParameter("stock");
            String categoryId = request.getParameter("category_id");
            String sort = request.getParameter("sort");
            String status = request.getParameter("status");


            //2.获取数据
            //2.1 创建product对象
            //Product product = new Product();
            //2.2 给对象赋值
            product.setName(name);

            //product.setLogo(logo);

            product.setPrice(new BigDecimal(price));
            product.setSale(Integer.parseInt(sale));
            product.setStock(Integer.parseInt(stock));
            product.setCategoryId(Integer.parseInt(categoryId));
            product.setStatus(Integer.parseInt(status));
            product.setSort(Integer.parseInt(sort));
            //2.3 创建对象articleService对象
            //2.4 调用insert方法
            productService.save(product);
            //3.转发或跳转
            response.sendRedirect("/admin/product/list");


        } else {

            //2.获取数据
            //2.1 获取所有分类
            CategoryServiceImpl categoryService = new CategoryServiceImpl();
            List<Category> categories = categoryService.findAll();

            //3.转发或跳转
            //3.1 转发数据
            request.setAttribute("categories", categories);
            request.setAttribute("product", product);
            //3.2 重定向
            request.getRequestDispatcher("/admin/product_edit.jsp").forward(request, response);
        }
    }

    public void del(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1. 接收参数
        int id = Integer.parseInt(request.getParameter("id"));
        //2. 处理数据
        productService.del(id);
        //3. 重定向或转发
        response.sendRedirect("/admin/product/list");
    }

}
